var moon = moon || {};
(function (m, w) {
    if (layui === undefined) {
        throw "moon webuploader need layui";
    }

    if (WebUploader === undefined) {
        throw "moon webuploader need WebUploader";
    }

    //详细文档: http://gmuteam.github.io/webuploader/doc/index.html
    var _default = {
        pick: {
            id: '#filePicker',
            multiple: false
        },
        server: "/hycj/files",
        fileVal: "file",
        swf: "Uploader.swf"
    };
    m.webuploader = function (opts) {
        var uploader = WebUploader.create($.extend(_default, opts));
        /******************** 绑定事件 ********************/
        !opts.beforeFileQueued || uploader.on("beforeFileQueued", opts.beforeFileQueued);
        !opts.fileQueued || uploader.on("fileQueued", opts.fileQueued);
        !opts.filesQueued || uploader.on("filesQueued", opts.filesQueued);
        !opts.fileDequeued || uploader.on("fileDequeued", opts.fileDequeued);
        !opts.startUpload || uploader.on("startUpload", opts.startUpload);
        !opts.stopUpload || uploader.on("stopUpload", opts.stopUpload);
        !opts.uploadFinished || uploader.on("uploadFinished", opts.uploadFinished);
        !opts.uploadStart || uploader.on("uploadStart", opts.uploadStart);
        !opts.uploadBeforeSend || uploader.on("uploadBeforeSend", opts.uploadBeforeSend);
        !opts.uploadAccept || uploader.on("uploadAccept", opts.uploadAccept);
        !opts.uploadProgress || uploader.on("uploadProgress", opts.uploadProgress);
        !opts.uploadError || uploader.on("uploadError", opts.uploadError);
        !opts.uploadSuccess || uploader.on("uploadSuccess", opts.uploadSuccess);
        !opts.uploadComplete || uploader.on("uploadComplete", opts.uploadComplete);
        !opts.error || uploader.on("error", opts.error);
        /******************** /绑定事件 ********************/
        /**
         * 上传按钮
         */
        if (opts.uploadButton) {
            $(opts.uploadButton).click(function () {
                uploader.upload();
            });
        }
        return uploader;
    };

    /**
     * 将字节文件大小处理为可读的文件大小米搜啊胡
     * @param size
     */
    m.makeFileSizeReadable = function (size) {
        return WebUploader.formatSize(size);
    };

    var dfd = $.Deferred();

    layui.use(["layer", 'element'], function () {
        var element = layui.element;
        var layer = layui.layer;
        var $fileContainer,//图片预览容器
            uploaderRet, //上传结果
            uploader,//文件上传组件
            serverPath = {};//文件上传路径，key为文件id，value为文件服务器路径

        /**
         * 增加上传表单元素
         */
        function addUploaderElementIfNecessary() {
            if ($("[component-name='webUploader']").size() == 0) {
                $("body").append('<script type="text/html" component-name="webUploader"><div class="webuploader">\n' +
                    '    <!--用来存放文件信息-->\n' +
                    '    <div id="fileContainer" class="uploader-list"><div class="add-more" id="webUploader_addMore"></div></div>\n' +
                    '    <div class="btns">\n' +
                    '        <div id="filePicker">点击选择文件</div>\n' +
                    //                    '        <button id="ctlBtn" class="btn btn-default">开始上传</button>\n' +
                    '    </div>\n' +
                    '</div></' + "script>");

            }
        }

        /**
         * 初始化文件上传组件
         */
        function initUploader() {
            var uploader = m._uploader_instance;
            //销毁已有实例
            if (uploader != undefined) {
                uploader.destroy();
                // return uploader;
            }
            //新创建实例
            uploader = moon.webuploader({
                paste: document.body,
                fileQueued: function (file) {
                    var uploader = this;
                    uploader.makeThumb(file, function (error, ret) {
                        if (error) {
                            alert("预览错误");
                        } else {
                            $fileContainer.find(".add-more").before('<div class="image-item init" data-file-id="' + file.id + '">' +
                                '<div class="toolbar">' +
                                '<span class="remove" data-file-id="' + file.id + '">&times;</span>' +
                                '</div>' +
                                '<img alt="" src="' + ret + '" />' +
                                '<div class="layui-progress  layui-progress-big"  lay-filter="progress-' + file.id + '" lay-showPercent="true">\n' +
                                '  <div class="layui-progress-bar layui-bg-green" lay-percent="0%"></div>\n' +
                                '</div>' +
                                '<div class="file-desc">' + moon.makeFileSizeReadable(file.size) + '</div>' +
                                '</div>'
                            );
                            $(".webuploader").addClass("file-queued");
                            element.render("progress", "progress-" + file.id);
                        }
                    });

                },
                fileDequeued: function (file) {
                    $(".image-item[data-file-id='" + file.id + "']").remove();
                    if ($(".webuploader .image-item").length == 0) {
                        $(".webuploader").removeClass("file-queued");
                    }

                },
                beforeFileQueued: function (file) {
                    if (file.size > 1024 * 1024) {
                        layer.msg("单个文件大小不能超过1M", {icon: 2});
                        return false;
                    }
                },
                uploadSuccess: function (file, response) {
                    if (response.code == "200") {
                        serverPath[file.id] = response.datas;
                        element.progress('progress-' + file.id, "100%");
                    }
                },
                uploadProgress: function (file, percentage) {
                    element.progress('progress-' + file.id, ((percentage * 100).toFixed(2) - 0.1) + "%");
                },
                uploadStart: function (file) {
                    $(".image-item[data-file-id='" + file.id + "']").removeClass("init");
                }

            });
            // uploader.addButton({
            //     id: "#webUploader_addMore",
            //     innerHTML: "+"
            // });

            m._uploader_instance = uploader;
            return uploader;
        }

        /**
         * 绑定全局事件，删除待传输文件
         */
        function bindGlobalEvent() {
            if (m._uploader_event_binded) {
                return;
            }
            m._uploader_event_binded = true;
            $(document).on("click", ".webuploader .remove", function (e) {
                var fileId = $(e.target).attr("data-file-id");
                if (fileId && uploader) {
                    uploader.removeFile(fileId);
                }
            });

            $(document).on("click", ":text.show-uploader", function (e) {
                showWebUploader({
                    input: $(e.target)
                });
            });
        }

        var _defaultOpts = {
            callback: null,//上传回调
            area: ['600px']

        };

        /**
         * 显示文件上传对话框
         */
        function showWebUploader(opts) {
            opts = $.extend({}, _defaultOpts, opts);
            addUploaderElementIfNecessary();
            layer.open({
                title: '文件上传',
                type: 1,
                area: opts.area,
                content: $("[ component-name='webUploader']").html(),
                success: function () {
                    $fileContainer = $("#fileContainer");
                    uploader = initUploader();
                },
                yes: function (index, layero) {
                    uploader.upload();
                },
                btn2: function (index, layero) {
                    if (uploader.isInProgress()) {
                        layer.msg("文件正在上传处理中，请稍后.", {icon: 2});
                        return false;
                    }
                    uploaderRet = [];
                    $.each(uploader.getFiles("complete"), function (index, item) {
                        var path = serverPath[item.id];
                        if (path) {
                            uploaderRet.push({path: path});
                        }
                    });
                    opts.callback && opts.callback.call(uploader, uploaderRet);

                    //如果没有回调，则尝试直接填充表单项。多个逗号分隔
                    if (!opts.callback && opts.input) {
                        var pathRet = "";
                        $.each(uploaderRet, function (index, path) {
                            pathRet += "," + path.path;
                        });
                        $(opts.input).val(pathRet.substring(1));
                    }
                    layer.close(index);
                },
                btn3: function (index, layero) {
                    layer.close(index);
                },
                btn: ['上传', '确定', '取消']

            });

        }

        bindGlobalEvent();
        dfd.resolve(showWebUploader);
    });

    m.uploader = function (opts) {
        dfd.done(function (fun) {
            fun.call(w, opts);
        });
    };
})(moon, window);